package com.github.binarywang.demo.wechat.handler;

import com.github.binarywang.demo.wechat.builder.*;
import com.github.binarywang.demo.wechat.utils.JsonUtils;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.*;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
public class MsgHandler extends AbstractHandler {

  @Override
  public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                  Map<String, Object> context, WxMpService weixinService,
                                  WxSessionManager sessionManager) {

    if (!wxMessage.getMsgType().equals(XmlMsgType.EVENT)) {
      //TODO 可以选择将消息保存到本地
    }

    //当用户输入关键词如“你好”，“客服”等，并且有客服在线时，把消息转发给在线客服
    try {
      if (StringUtils.startsWithAny(wxMessage.getContent(), "你好", "客服")
          && weixinService.getKefuService().kfOnlineList()
          .getKfOnlineList().size() > 0) {
        return WxMpXmlOutMessage.TRANSFER_CUSTOMER_SERVICE()
            .fromUser(wxMessage.getToUser())
            .toUser(wxMessage.getFromUser()).build();
      }

      if (StringUtils.startsWithAny(wxMessage.getContent(), "模板")) {
        return sendTemplate(wxMessage, weixinService);
      }

      if (StringUtils.startsWithAny(wxMessage.getContent(), "图片")) {
        return sendImage(wxMessage, weixinService);
      }

      if (StringUtils.startsWithAny(wxMessage.getContent(), "音乐")) {
        return sendMusic(wxMessage, weixinService);
      }

      if (StringUtils.startsWithAny(wxMessage.getContent(), "语音")) {
        return sendVoice(wxMessage, weixinService);
      }

      if (StringUtils.startsWithAny(wxMessage.getContent(), "视频")) {
        return sendVideo(wxMessage, weixinService);
      }

      if (StringUtils.startsWithAny(wxMessage.getContent(), "新闻")) {
        return sendNews(wxMessage, weixinService);
      }
    } catch (WxErrorException e) {
      e.printStackTrace();
    }


    //TODO 组装回复消息
    String content = "收到信息内容：" + JsonUtils.toJson(wxMessage);

    return new TextBuilder().build(content, wxMessage, weixinService);

  }

  /**
   * 模板消息
   * @param wxMessage
   * @param weixinService
   * @return
   * @throws WxErrorException
   */
  private WxMpXmlOutMessage sendTemplate(WxMpXmlMessage wxMessage, WxMpService weixinService) throws WxErrorException{
    SimpleDateFormat dateFormat = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss.SSS");
    WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
            .toUser(wxMessage.getFromUser())
            .templateId("-rkvkFMwqNigRohS0el2zDibFyDaBQsFPjgx7jdxpxI").build();
    templateMessage.addWxMpTemplateData(
            new WxMpTemplateData("first", "您好，您持有的茅台股份即将上市了。", "#FF00FF"));
    templateMessage.addWxMpTemplateData(
            new WxMpTemplateData("name", "茅台股份"));
    templateMessage.addWxMpTemplateData(
            new WxMpTemplateData("date", dateFormat.format(new Date())));
    templateMessage.addWxMpTemplateData(
            new WxMpTemplateData("remark", "如有疑问，请致电95536。"));
//    templateMessage.setUrl("http://weixin.qq.com/download");
    String msgId = weixinService.getTemplateMsgService().sendTemplateMsg(templateMessage);
    System.out.println("模板消息发送成功：" + msgId);
    return null;
  }

  /**
   * 图片消息
   * @param wxMessage
   * @param wxMpService
   * @return
   * @throws WxErrorException
   */
  private WxMpXmlOutMessage sendImage(WxMpXmlMessage wxMessage, WxMpService wxMpService) throws WxErrorException{
    WxMediaUploadResult wxMediaUploadResult = wxMpService.getMaterialService()
            .mediaUpload(WxConsts.MediaFileType.IMAGE, "jpeg", ClassLoader.getSystemResourceAsStream("mm.jpeg"));
    return new ImageBuilder().build(wxMediaUploadResult.getMediaId(), wxMessage, wxMpService);
  }

  /**
   * 音乐消息
   * @param wxMessage
   * @param wxMpService
   * @return
   * @throws WxErrorException
   */
  private WxMpXmlOutMessage sendMusic(WxMpXmlMessage wxMessage, WxMpService wxMpService) throws WxErrorException{
    WxMediaUploadResult wxMediaUploadResult = wxMpService.getMaterialService()
            .mediaUpload(WxConsts.MediaFileType.IMAGE, "jpeg", ClassLoader.getSystemResourceAsStream("mm.jpeg"));
    String musicUrl = "http://sc1.111ttt.cn:8282/2017/1/11m/11/304112003368.m4a?tflag=1517551201&amp;pin=61799d31720c165e2ef82b942d0e89ef#.mp3";
    String hqMusicUrl = "http://sc1.111ttt.cn:8282/2017/1/11m/11/304112003368.m4a?tflag=1517551201&amp;pin=61799d31720c165e2ef82b942d0e89ef#.mp3";
    return new MusicBuilder().build("title", "desc", hqMusicUrl, musicUrl, wxMediaUploadResult.getMediaId(), wxMessage, wxMpService);
  }

  /**
   * 语音消息
   * @param wxMessage
   * @param wxMpService
   * @return
   * @throws WxErrorException
   */
  private WxMpXmlOutMessage sendVoice(WxMpXmlMessage wxMessage, WxMpService wxMpService) throws WxErrorException{
    /*
     * 语音素材
     */
    WxMediaUploadResult uploadMediaRes = wxMpService.getMaterialService()
            .mediaUpload(WxConsts.MediaFileType.VOICE, "mp3", ClassLoader
                    .getSystemResourceAsStream("mm.mp3"));
    return new VoiceBuilder().build(uploadMediaRes.getMediaId(), wxMessage, wxMpService);
  }

  /**
   * 视频消息
   * @param wxMessage
   * @param wxMpService
   * @return
   * @throws WxErrorException
   */
  private WxMpXmlOutMessage sendVideo(WxMpXmlMessage wxMessage, WxMpService wxMpService) throws WxErrorException{
    WxMediaUploadResult uploadMediaRes = wxMpService.getMaterialService()
            .mediaUpload(WxConsts.MediaFileType.VIDEO, "mp4", ClassLoader
                    .getSystemResourceAsStream("mm.mp4"));
    return new VideoBuilder().build("title", "desc", uploadMediaRes.getMediaId(), wxMessage, wxMpService);
  }

  /**
   * 新闻消息
   * @param wxMessage
   * @param wxMpService
   * @return
   * @throws WxErrorException
   */
  private WxMpXmlOutMessage sendNews(WxMpXmlMessage wxMessage, WxMpService wxMpService) throws WxErrorException{
    WxMpXmlOutNewsMessage.Item item = new WxMpXmlOutNewsMessage.Item();
    item.setDescription("description");
    item.setPicUrl("https://gitee.com/assets/qrcode-weixin-8ab7378f5545710bdb3ad5c9d17fedfe.jpg");
    item.setTitle("title");
    item.setUrl("https://gitee.com//lc77/ctDevWiki/wikis/");

    WxMpXmlOutNewsMessage.Item item1 = new WxMpXmlOutNewsMessage.Item();
    item1.setDescription("description1");
    item1.setPicUrl("http://mmbiz.qpic.cn/mmbiz/PiajxSqBRaEIQxibpLbyuSK45r8VZ2rGTdMj1At2I0bZlZpfMgHYOoZV3vhC5u0ubb6UvgoHDE1WN95rv0AOoNvQ/0?wx_fmt=png");
    item1.setTitle("title1");
    item1.setUrl("https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419318292&token=&lang=zh_CN");

    return new NewsBuilder().build(wxMessage, wxMpService, item, item1);
  }

}
